package org.codingq92.pritice.socket;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP Server
 *
 * @author: CodingQ92
 * @date: 2025/6/18 00:11
 */
public class TcpServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(9000)) {
            while (true) {
                Socket accept = serverSocket.accept();
                System.out.println(accept.getRemoteSocketAddress() + ">>>连接成功!!!");
                new ServerThread(accept).start();
                Thread.sleep(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class ServerThread extends Thread {
        private final Socket socket;

        public ServerThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                DataInputStream dis = new DataInputStream(inputStream);
                while (true) {
                    try {
                        String msg = dis.readUTF();
                        System.out.println("来自[" + socket.getRemoteSocketAddress() + "]的消息: " + msg);
                    } catch (EOFException e) {
                        dis.close();
                        System.out.println("客户端[" + socket.getRemoteSocketAddress() + "]已断开!!!");
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
